package com.ruoyi.common.utils;

import com.ruoyi.common.config.SmsConfig;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 五粮液短信发送基础类
 */
@Component
public class SmsUtil {

    //短信网关配置
    private static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);





    /**
     * 短信发送
     * 实际返回内容为（不同场景返回的数据略有差异）：
     * “result=错误代码&description=错误描述&faillist=失败号码列表”
     * “result=0&description=发送短信成功&taskid=任务编号&&faillist=&task_id=任务编号”
     * “result=错误代码&description=错误描述”
     *
     * @param mobileNo
     * @param message
     * @return
     */
    public static Map<String, String> sendMessage(String message, String mobileNo) {
        //TODO 短信提示 开关属性注入失败
        // 解决:利用set方法注入属性, set方法为非静态方法,属性为静态属性
        logger.info("短信开关：enabled=" + SmsConfig.enabled);
        logger.info("短信发送前的参数：message=" + message);
        logger.info("短信发送前的参数：mobileNo=" + mobileNo);
        Map<String, String> map = new HashMap<>();

        if(!SmsConfig.enabled){
            return map;
        }
        String info = null;
        try {
            HttpClient httpclient = new HttpClient();
            PostMethod post = getPostMethod(message, mobileNo);
            httpclient.executeMethod(post);
            info = new String(post.getResponseBody(), "gbk");
            logger.info("短信发送返回结果：" + info);

            String[] resultArr = info.split("&");
            if (resultArr.length > 1) {
                map.put("code", resultArr[0].split("=")[1]);
                map.put("message", resultArr[1].split("=")[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", "-1");
            map.put("message", "系统错误");
            logger.error("短信发送失败。" + e.getMessage());
        }
        return map;
    }

    private static PostMethod getPostMethod(String message, String phone) {
        PostMethod post = new PostMethod(SmsConfig.uri);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "gbk");
        post.addParameter("SpCode", SmsConfig.cpcode);
        post.addParameter("LoginName", SmsConfig.user);
        post.addParameter("Password", SmsConfig.pwd);
        post.addParameter("MessageContent", message);
        post.addParameter("UserNumber", phone);
        post.addParameter("SerialNumber", "");
        post.addParameter("ScheduleTime", "");
        post.addParameter("ExtendAccessNum", "");
        post.addParameter("f", "1");
        return post;
    }



    // public static void main(String[] args)
    // {
    //     String message = "【五粮液】纪检监察组(单位)罗鑫光，您好！在线监督平台提示:回执:凌义芳接收了关于征求《2021年度国有企业纪检监察工作要点》意见的函";
    //     SmsUtil.sendMessage(message, "18190558505");
    // }
}
